import {
	Button,
	IconButton,
	Rating,
	Stack,
	TextField,
	Typography,
	styled,
} from '@mui/material'
import { useState } from 'react'
import { useParams } from 'react-router-dom'
import DeleteOutlineIcon from '@mui/icons-material/DeleteOutline'
import {
	useAddProductReviewMutation,
	useGetProductQuery,
	useDeleteProductReviewMutation,
} from '../../api/productsApiSlice'
import { useAppSelector } from '../../hooks'
import { selectUser } from '../../store/reducers/selectors'

const ADD_REVIEW_BUTTON = 'ADD_REVIEW_BUTTON'
const REVIEW_RATING = 'REVIEW_RATING'
const REVIEW_INPUT_TEXTFIELD = 'REVIEW_INPUT_TEXTFIELD'
const PUBLISH_REVIEW_BUTTON = 'PUBLISH_REVIEW_BUTTON'
const DELETE_REVIEW_BUTTON = 'DELETE_REVIEW_BUTTON'

const StyledContainer = styled('div')(() => ({
	display: 'flex',
	marginBottom: '10px',
	width: '100%',
	flexDirection: 'column',
}))

const StyledButton = styled(Button)(() => ({
	marginTop: '16px',
	width: '160px',
	height: '40px',
	borderRadius: '55px',
	background: '#FFE44D',
	border: '0px',
	'&': {
		color: '#1A1A1A',
		textTransform: 'none',
	},
}))

const StyledMineReview = styled(Stack)(() => ({
	border: '1px solid',
	borderRadius: '12px',
	padding: '12px',
	gap: '12px',
	margin: '24px 0px 24px 0px',
	background: '#FFEECC',
}))

const StyledReview = styled(Stack)(() => ({
	border: '1px solid',
	borderRadius: '12px',
	padding: '12px',
	gap: '12px',
	margin: '24px 0px 24px 0px',
}))

const StyledDTrashIcon = styled(DeleteOutlineIcon)(() => ({
	color: '#7B8E98',
}))

const Reviews = () => {
	const { productId } = useParams()
	const user = useAppSelector(selectUser)
	const { data: productData } = useGetProductQuery({ id: productId || '' })
	const [addProductReviewMutationFn] = useAddProductReviewMutation()
	const [deleteProductReviewMutationFn] = useDeleteProductReviewMutation()

	const [mineReviewEnabled, setMineReviewEnabled] = useState(false)
	const [mineReviewRating, setMineReviewRating] = useState(0)
	const [reviewText, setReviewText] = useState('')

	const handleResetReview = () => {
		setMineReviewEnabled(false)
		setMineReviewRating(0)
		setReviewText('')
	}

	const handleAddReview = () => {
		if (productData?._id)
			addProductReviewMutationFn({
				productId: productData._id,
				review: { rating: mineReviewRating, text: reviewText },
			}).then(handleResetReview)
	}

	const handleDeleteReview = (reviewId: string) => {
		if (productData?._id)
			deleteProductReviewMutationFn({
				productId: productData._id,
				review: { _id: reviewId, rating: mineReviewRating, text: reviewText },
			}).then(handleResetReview)
	}

	return (
		<StyledContainer>
			{mineReviewEnabled ? (
				<Stack direction={'row'} spacing={2}>
					<StyledButton variant='outlined' onClick={handleResetReview}>
						<Typography>Отмена</Typography>
					</StyledButton>

					<StyledButton
						data-testid={PUBLISH_REVIEW_BUTTON}
						variant='outlined'
						disabled={reviewText.length === 0 || mineReviewRating < 1}
						onClick={handleAddReview}
					>
						<Typography>Опубликовать</Typography>
					</StyledButton>
				</Stack>
			) : (
				<StyledButton
					data-testid={ADD_REVIEW_BUTTON}
					variant='outlined'
					onClick={() => setMineReviewEnabled(true)}
				>
					<Typography>Написать отзыв</Typography>
				</StyledButton>
			)}

			<Stack>
				{mineReviewEnabled && (
					<StyledMineReview>
						<Rating
							data-testid={REVIEW_RATING}
							name='half-rating-read'
							value={mineReviewRating}
							onChange={(event, newValue) =>
								setMineReviewRating(Number(newValue))
							}
							precision={1}
						/>
						<Stack direction={'row'} spacing={2}>
							<Typography>Вы</Typography>
						</Stack>
						<TextField
							data-testid={REVIEW_INPUT_TEXTFIELD}
							multiline
							value={reviewText}
							onChange={(event) => setReviewText(event.target.value)}
						/>
					</StyledMineReview>
				)}
				{productData?.reviews
					?.filter(({ text }) => text.length > 0)
					.sort((a, b) => Date.parse(b.updated_at) - Date.parse(a.updated_at))
					.map((review) => (
						<StyledReview key={review._id}>
							<Rating
								name='half-rating-read'
								value={review.rating}
								precision={0.5}
								readOnly
							/>
							<Stack direction={'row'} spacing={2} alignItems={'center'}>
								<Typography>{review.author.name}</Typography>
								<Typography>
									{new Date(review.updated_at)
										.toLocaleDateString()
										.replaceAll('/', '.')}
								</Typography>
								<IconButton
									data-testid={DELETE_REVIEW_BUTTON}
									onClick={() => handleDeleteReview(review._id)}
								>
									{review.author._id === user?._id && <StyledDTrashIcon />}
								</IconButton>
							</Stack>
							<TextField multiline disabled value={review.text} />
						</StyledReview>
					))}
			</Stack>
		</StyledContainer>
	)
}

export default Reviews
